package com.monitor.ui;

import com.monitor.filter.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

/**
 * 防护中心面板，包含文字过滤、网址拦截、图像识别和进程拦截功能
 */
public class ProtectionPanel extends JPanel {
    private static final Color MAIN_COLOR = new Color(0, 120, 215);

    private TextFilter textFilter;
    private UrlFilter urlFilter;
    private ImageFilter imageFilter;
    private ProcessFilter processFilter;

    public ProtectionPanel() {
        // 初始化过滤器
        textFilter = new TextFilter();
        urlFilter = new UrlFilter();
        imageFilter = new ImageFilter();
        processFilter = new ProcessFilter();

        // 设置面板
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        // 创建标题面板
        JPanel titlePanel = createTitlePanel("防护中心");
        add(titlePanel, BorderLayout.NORTH);

        // 创建内容面板
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setBackground(Color.WHITE);

        // 添加各功能项
        contentPanel.add(createFeaturePanel("上网内容数据防护", "保护上网环境健康安全，过滤图片、视频等", this::showImageFilterPanel));
        contentPanel.add(createFeaturePanel("实时网站效果监控", "在黑名单中设置禁止访问的网站，禁止游戏访问", this::showUrlFilterPanel));
        contentPanel.add(createFeaturePanel("敏感关键字防护", "禁止上网过程中搜索和访问敏感关键字", this::showTextFilterPanel));
        contentPanel.add(createFeaturePanel("敏感进程防护", "禁止运行指定程序（如网络游戏、聊天软件）", this::showProcessFilterPanel));

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(contentPanel);
        scrollPane.setBorder(null);
        add(scrollPane, BorderLayout.CENTER);
    }

    private JPanel createTitlePanel(String title) {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(MAIN_COLOR);
        panel.setPreferredSize(new Dimension(800, 40));

        JLabel titleLabel = new JLabel(title, JLabel.CENTER);
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        panel.add(titleLabel, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createFeaturePanel(String title, String description, ActionListener action) {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.WHITE);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 60));
        panel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY));

        JPanel iconPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        iconPanel.setBackground(Color.WHITE);
        iconPanel.setPreferredSize(new Dimension(60, 60));

        // 创建一个圆形图标
        JPanel circleIcon = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(new Color(0, 200, 0));
                g2d.fillOval(0, 0, 20, 20);
                g2d.dispose();
            }
        };
        circleIcon.setPreferredSize(new Dimension(20, 20));
        circleIcon.setOpaque(false);

        iconPanel.add(circleIcon);

        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
        textPanel.setBackground(Color.WHITE);

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel descLabel = new JLabel(description);
        descLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        descLabel.setForeground(Color.GRAY);
        descLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        textPanel.add(Box.createVerticalStrut(10));
        textPanel.add(titleLabel);
        textPanel.add(Box.createVerticalStrut(5));
        textPanel.add(descLabel);
        textPanel.add(Box.createVerticalStrut(10));

        panel.add(iconPanel, BorderLayout.WEST);
        panel.add(textPanel, BorderLayout.CENTER);

        // 添加点击事件
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (action != null) {
                    action.actionPerformed(new ActionEvent(panel, ActionEvent.ACTION_PERFORMED, title));
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                panel.setBackground(new Color(240, 245, 255));
                textPanel.setBackground(new Color(240, 245, 255));
                iconPanel.setBackground(new Color(240, 245, 255));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                panel.setBackground(Color.WHITE);
                textPanel.setBackground(Color.WHITE);
                iconPanel.setBackground(Color.WHITE);
            }
        });

        return panel;
    }

    private void showTextFilterPanel(ActionEvent e) {
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "敏感关键字防护", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建关键词列表
        DefaultListModel<String> keywordModel = new DefaultListModel<>();
        for (String keyword : textFilter.getKeywords()) {
            keywordModel.addElement(keyword);
        }

        JList<String> keywordList = new JList<>(keywordModel);
        JScrollPane listScroll = new JScrollPane(keywordList);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton addButton = new JButton("添加");
        JButton removeButton = new JButton("删除");
        JButton closeButton = new JButton("关闭");

        // 创建灵敏度选择
        JPanel sensitivityPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        sensitivityPanel.add(new JLabel("灵敏度设置："));

        JRadioButton highBtn = new JRadioButton("高");
        JRadioButton mediumBtn = new JRadioButton("中");
        JRadioButton lowBtn = new JRadioButton("低");

        // 设置当前灵敏度
        switch (textFilter.getSensitivity()) {
            case HIGH:
                highBtn.setSelected(true);
                break;
            case MEDIUM:
                mediumBtn.setSelected(true);
                break;
            case LOW:
                lowBtn.setSelected(true);
                break;
        }

        ButtonGroup sensitivityGroup = new ButtonGroup();
        sensitivityGroup.add(highBtn);
        sensitivityGroup.add(mediumBtn);
        sensitivityGroup.add(lowBtn);

        sensitivityPanel.add(highBtn);
        sensitivityPanel.add(mediumBtn);
        sensitivityPanel.add(lowBtn);

        // 添加事件监听
        addButton.addActionListener(evt -> {
            String keyword = JOptionPane.showInputDialog(dialog, "请输入要添加的关键词：");
            if (keyword != null && !keyword.trim().isEmpty()) {
                textFilter.addKeyword(keyword.trim());
                keywordModel.addElement(keyword.trim());
            }
        });

        removeButton.addActionListener(evt -> {
            int selectedIndex = keywordList.getSelectedIndex();
            if (selectedIndex != -1) {
                String keyword = keywordModel.getElementAt(selectedIndex);
                textFilter.removeKeyword(keyword);
                keywordModel.remove(selectedIndex);
            }
        });

        closeButton.addActionListener(evt -> dialog.dispose());

        highBtn.addActionListener(evt -> textFilter.setSensitivity(FilterSensitivity.HIGH));
        mediumBtn.addActionListener(evt -> textFilter.setSensitivity(FilterSensitivity.MEDIUM));
        lowBtn.addActionListener(evt -> textFilter.setSensitivity(FilterSensitivity.LOW));

        buttonPanel.add(addButton);
        buttonPanel.add(removeButton);
        buttonPanel.add(closeButton);

        contentPanel.add(new JLabel("敏感关键词列表："), BorderLayout.NORTH);
        contentPanel.add(listScroll, BorderLayout.CENTER);
        contentPanel.add(sensitivityPanel, BorderLayout.SOUTH);

        dialog.add(contentPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private void showUrlFilterPanel(ActionEvent e) {
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "网址过滤设置", true);
        dialog.setSize(600, 500);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JTabbedPane tabbedPane = new JTabbedPane();

        // 黑名单面板
        JPanel blacklistPanel = new JPanel(new BorderLayout(10, 10));
        blacklistPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        DefaultListModel<String> blacklistModel = new DefaultListModel<>();
        for (String url : urlFilter.getBlacklist()) {
            blacklistModel.addElement(url);
        }

        JList<String> blacklistList = new JList<>(blacklistModel);
        JScrollPane blacklistScroll = new JScrollPane(blacklistList);

        JPanel blacklistButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton addBlacklistButton = new JButton("添加");
        JButton removeBlacklistButton = new JButton("删除");

        addBlacklistButton.addActionListener(evt -> {
            String url = JOptionPane.showInputDialog(dialog, "请输入要添加到黑名单的网址：");
            if (url != null && !url.trim().isEmpty()) {
                urlFilter.addToBlacklist(url.trim());
                blacklistModel.addElement(url.trim());
            }
        });

        removeBlacklistButton.addActionListener(evt -> {
            int selectedIndex = blacklistList.getSelectedIndex();
            if (selectedIndex != -1) {
                String url = blacklistModel.getElementAt(selectedIndex);
                urlFilter.removeFromBlacklist(url);
                blacklistModel.remove(selectedIndex);
            }
        });

        blacklistButtonPanel.add(addBlacklistButton);
        blacklistButtonPanel.add(removeBlacklistButton);

        blacklistPanel.add(new JLabel("黑名单网址列表："), BorderLayout.NORTH);
        blacklistPanel.add(blacklistScroll, BorderLayout.CENTER);
        blacklistPanel.add(blacklistButtonPanel, BorderLayout.SOUTH);

        // 白名单面板
        JPanel whitelistPanel = new JPanel(new BorderLayout(10, 10));
        whitelistPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        DefaultListModel<String> whitelistModel = new DefaultListModel<>();
        for (String url : urlFilter.getWhitelist()) {
            whitelistModel.addElement(url);
        }

        JList<String> whitelistList = new JList<>(whitelistModel);
        JScrollPane whitelistScroll = new JScrollPane(whitelistList);

        JPanel whitelistButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton addWhitelistButton = new JButton("添加");
        JButton removeWhitelistButton = new JButton("删除");

        addWhitelistButton.addActionListener(evt -> {
            String url = JOptionPane.showInputDialog(dialog, "请输入要添加到白名单的网址：");
            if (url != null && !url.trim().isEmpty()) {
                urlFilter.addToWhitelist(url.trim());
                whitelistModel.addElement(url.trim());
            }
        });

        removeWhitelistButton.addActionListener(evt -> {
            int selectedIndex = whitelistList.getSelectedIndex();
            if (selectedIndex != -1) {
                String url = whitelistModel.getElementAt(selectedIndex);
                urlFilter.removeFromWhitelist(url);
                whitelistModel.remove(selectedIndex);
            }
        });

        whitelistButtonPanel.add(addWhitelistButton);
        whitelistButtonPanel.add(removeWhitelistButton);

        whitelistPanel.add(new JLabel("白名单网址列表："), BorderLayout.NORTH);
        whitelistPanel.add(whitelistScroll, BorderLayout.CENTER);
        whitelistPanel.add(whitelistButtonPanel, BorderLayout.SOUTH);

        // 灵敏度设置面板
        JPanel sensitivityPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        sensitivityPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        sensitivityPanel.add(new JLabel("灵敏度设置："));

        JRadioButton highBtn = new JRadioButton("高");
        JRadioButton mediumBtn = new JRadioButton("中");
        JRadioButton lowBtn = new JRadioButton("低");

        // 设置当前灵敏度
        switch (urlFilter.getSensitivity()) {
            case HIGH:
                highBtn.setSelected(true);
                break;
            case MEDIUM:
                mediumBtn.setSelected(true);
                break;
            case LOW:
                lowBtn.setSelected(true);
                break;
        }

        ButtonGroup sensitivityGroup = new ButtonGroup();
        sensitivityGroup.add(highBtn);
        sensitivityGroup.add(mediumBtn);
        sensitivityGroup.add(lowBtn);

        sensitivityPanel.add(highBtn);
        sensitivityPanel.add(mediumBtn);
        sensitivityPanel.add(lowBtn);

        highBtn.addActionListener(evt -> urlFilter.setSensitivity(FilterSensitivity.HIGH));
        mediumBtn.addActionListener(evt -> urlFilter.setSensitivity(FilterSensitivity.MEDIUM));
        lowBtn.addActionListener(evt -> urlFilter.setSensitivity(FilterSensitivity.LOW));

        // 添加选项卡
        tabbedPane.addTab("黑名单", blacklistPanel);
        tabbedPane.addTab("白名单", whitelistPanel);

        // 底部按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(evt -> dialog.dispose());
        buttonPanel.add(closeButton);

        dialog.add(tabbedPane, BorderLayout.CENTER);
        dialog.add(sensitivityPanel, BorderLayout.NORTH);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private void showImageFilterPanel(ActionEvent e) {
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "图像过滤设置", true);
        dialog.setSize(400, 200);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel sensitivityPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        sensitivityPanel.add(new JLabel("图像过滤灵敏度设置："));

        JRadioButton highBtn = new JRadioButton("高");
        JRadioButton mediumBtn = new JRadioButton("中");
        JRadioButton lowBtn = new JRadioButton("低");

        // 设置当前灵敏度
        switch (imageFilter.getSensitivity()) {
            case HIGH:
                highBtn.setSelected(true);
                break;
            case MEDIUM:
                mediumBtn.setSelected(true);
                break;
            case LOW:
                lowBtn.setSelected(true);
                break;
        }

        ButtonGroup sensitivityGroup = new ButtonGroup();
        sensitivityGroup.add(highBtn);
        sensitivityGroup.add(mediumBtn);
        sensitivityGroup.add(lowBtn);

        sensitivityPanel.add(highBtn);
        sensitivityPanel.add(mediumBtn);
        sensitivityPanel.add(lowBtn);

        highBtn.addActionListener(evt -> imageFilter.setSensitivity(FilterSensitivity.HIGH));
        mediumBtn.addActionListener(evt -> imageFilter.setSensitivity(FilterSensitivity.MEDIUM));
        lowBtn.addActionListener(evt -> imageFilter.setSensitivity(FilterSensitivity.LOW));

        JTextArea descArea = new JTextArea("图像过滤器通过分析图像内容自动识别并拦截色情、暴力图片。\n" +
                "高灵敏度：可能会误报较多，但能拦截大部分不良图片\n" +
                "中灵敏度：平衡准确率和召回率\n" +
                "低灵敏度：减少误报，但可能会漏过一些不良图片");
        descArea.setEditable(false);
        descArea.setLineWrap(true);
        descArea.setWrapStyleWord(true);
        descArea.setBackground(dialog.getBackground());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(evt -> dialog.dispose());
        buttonPanel.add(closeButton);

        contentPanel.add(sensitivityPanel, BorderLayout.NORTH);
        contentPanel.add(descArea, BorderLayout.CENTER);

        dialog.add(contentPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private void showProcessFilterPanel(ActionEvent e) {
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "进程过滤设置", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建进程列表
        DefaultListModel<String> processModel = new DefaultListModel<>();
        for (String process : processFilter.getBlockedProcesses()) {
            processModel.addElement(process);
        }

        JList<String> processList = new JList<>(processModel);
        JScrollPane listScroll = new JScrollPane(processList);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton addButton = new JButton("添加");
        JButton removeButton = new JButton("删除");
        JButton refreshButton = new JButton("刷新进程");
        JButton closeButton = new JButton("关闭");

        // 创建灵敏度选择
        JPanel sensitivityPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        sensitivityPanel.add(new JLabel("灵敏度设置："));

        JRadioButton highBtn = new JRadioButton("高");
        JRadioButton mediumBtn = new JRadioButton("中");
        JRadioButton lowBtn = new JRadioButton("低");

        // 设置当前灵敏度
        switch (processFilter.getSensitivity()) {
            case HIGH:
                highBtn.setSelected(true);
                break;
            case MEDIUM:
                mediumBtn.setSelected(true);
                break;
            case LOW:
                lowBtn.setSelected(true);
                break;
        }

        ButtonGroup sensitivityGroup = new ButtonGroup();
        sensitivityGroup.add(highBtn);
        sensitivityGroup.add(mediumBtn);
        sensitivityGroup.add(lowBtn);

        sensitivityPanel.add(highBtn);
        sensitivityPanel.add(mediumBtn);
        sensitivityPanel.add(lowBtn);

        // 添加事件监听
        addButton.addActionListener(evt -> {
            String process = JOptionPane.showInputDialog(dialog, "请输入要禁止的进程名称：");
            if (process != null && !process.trim().isEmpty()) {
                processFilter.addBlockedProcess(process.trim());
                processModel.addElement(process.trim());
            }
        });

        removeButton.addActionListener(evt -> {
            int selectedIndex = processList.getSelectedIndex();
            if (selectedIndex != -1) {
                String process = processModel.getElementAt(selectedIndex);
                processFilter.removeBlockedProcess(process);
                processModel.remove(selectedIndex);
            }
        });

        refreshButton.addActionListener(evt -> {
            // 获取当前运行的进程列表
            java.util.List<String> runningProcesses = processFilter.getRunningProcesses();

            // 显示进程选择对话框
            JDialog processDialog = new JDialog(dialog, "选择要禁止的进程", true);
            processDialog.setSize(400, 300);
            processDialog.setLocationRelativeTo(dialog);

            DefaultListModel<String> runningModel = new DefaultListModel<>();
            for (String proc : runningProcesses) {
                runningModel.addElement(proc);
            }

            JList<String> runningList = new JList<>(runningModel);
            JScrollPane runningScroll = new JScrollPane(runningList);

            JPanel procButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            JButton addProcButton = new JButton("添加所选进程");
            JButton cancelButton = new JButton("取消");

            addProcButton.addActionListener(e1 -> {
                int[] indices = runningList.getSelectedIndices();
                for (int index : indices) {
                    String proc = runningModel.getElementAt(index);
                    // 提取进程名称
                    String procName = proc;
                    if (proc.contains(",")) {
                        procName = proc.split(",")[0].replace("\"", "");
                    }
                    processFilter.addBlockedProcess(procName);
                    if (!processModel.contains(procName)) {
                        processModel.addElement(procName);
                    }
                }
                processDialog.dispose();
            });

            cancelButton.addActionListener(e1 -> processDialog.dispose());

            procButtonPanel.add(addProcButton);
            procButtonPanel.add(cancelButton);

            processDialog.setLayout(new BorderLayout());
            processDialog.add(new JLabel("当前运行的进程："), BorderLayout.NORTH);
            processDialog.add(runningScroll, BorderLayout.CENTER);
            processDialog.add(procButtonPanel, BorderLayout.SOUTH);
            processDialog.setVisible(true);
        });

        closeButton.addActionListener(evt -> dialog.dispose());

        highBtn.addActionListener(evt -> processFilter.setSensitivity(FilterSensitivity.HIGH));
        mediumBtn.addActionListener(evt -> processFilter.setSensitivity(FilterSensitivity.MEDIUM));
        lowBtn.addActionListener(evt -> processFilter.setSensitivity(FilterSensitivity.LOW));

        buttonPanel.add(addButton);
        buttonPanel.add(removeButton);
        buttonPanel.add(refreshButton);
        buttonPanel.add(closeButton);

        contentPanel.add(new JLabel("禁止进程列表："), BorderLayout.NORTH);
        contentPanel.add(listScroll, BorderLayout.CENTER);
        contentPanel.add(sensitivityPanel, BorderLayout.SOUTH);

        dialog.add(contentPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    // 获取各过滤器实例
    public TextFilter getTextFilter() {
        return textFilter;
    }

    public UrlFilter getUrlFilter() {
        return urlFilter;
    }

    public ImageFilter getImageFilter() {
        return imageFilter;
    }

    public ProcessFilter getProcessFilter() {
        return processFilter;
    }
}
